﻿using System;
using System.Collections.Generic;
using QTPlugin;
using QTPlugin.Interop;
using System.Windows.Forms;
using System.IO;
using System.Drawing;
using Microsoft.Win32;
using System.Reflection;
using System.Runtime.InteropServices;

namespace Kawanon.QtHoney
{
	public class NWebBrowser : NativeWindow
	{
		private const uint WM_SETFOCUS = 0x0007;
		private const uint WM_SHOWWINDOW = 0x0018;
		private const uint WM_PAINT = 0x000F;

		protected override void WndProc(ref Message m)
		{
			//switch ((uint)m.Msg)
			//{
			//}

			base.WndProc(ref m);
		}
	}

	public static class Utility
	{
		[DllImport("user32.dll")]
		[return: MarshalAs(UnmanagedType.Bool)]
		static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);

		public static object ReflectGetFieldValue(object obj, string name)
		{
			MemberInfo[] members = (MemberInfo[])obj.GetType().GetMember(name,
				MemberTypes.Field, BindingFlags.Instance | BindingFlags.NonPublic);
			if (members == null || members.Length == 0)
			{
				return null;
			}
			FieldInfo field = (FieldInfo)members[0];
			return field.GetValue(obj);
		}

		//public static Stream GetResourceStream(string name)
		//{
		//    Assembly asm = Assembly.GetExecutingAssembly();
		//    string str = String.Format("{0}.res.{1}", typeof(Utility).Namespace, name);
		//    return asm.GetManifestResourceStream(str);
		//}

		public static void ShowForm(IPluginServer server, Form form)	// from GroupEditor
		{
			RECT rc = new RECT();
			if (GetWindowRect(server.ExplorerHandle, out rc))
			{
				form.StartPosition = FormStartPosition.Manual;
				form.Left = rc.left + (rc.Width - form.Width) / 2;
				form.Top = rc.top + (rc.Height - form.Height) / 2;
			}
			else
			{
				form.StartPosition = FormStartPosition.CenterScreen;
			}

			// ツールバーウィンドウを親に（ExplorerHandle は null が返るので）
			Control parent = Control.FromHandle(server.Handle);
			form.Show(parent);

			//MessageBox.Show(string.Format("{0} {1} {2} {3}", rc.right, rc.top, parent.Width, parent.Height ));
		}

		public static Control GetBandObject(IPluginServer server)
		{
			// QTTabBarClass を取得
			return Control.FromHandle(server.Handle);
		}

		public static bool IsDebugMode()
		{
			RegistryKey key = PluginInformation.OpenRegistryKey(false);
			if (key == null)
			{
				return false;
			}
			int val = (int)key.GetValue("Debug", 0);
			return val != 0;
		}

		public static void DoModal(IPluginServer server, MethodInvoker func)
		{
			if (server != null)
			{
				server.ExecuteCommand(Commands.SetModalState, true);
			}
			try
			{
				func();
			}
			finally
			{
				if (server != null)
				{
					server.ExecuteCommand(Commands.SetModalState, false);
				}
			}
		}

		public static DialogResult DoModal(IPluginServer server, Form form)
		{
			if (server != null)
			{
				server.ExecuteCommand(Commands.SetModalState, true);
			}
			try
			{
				return form.ShowDialog();
			}
			finally
			{
				if (server != null)
				{
					server.ExecuteCommand(Commands.SetModalState, false);
				}
			}
		}
	}

	public static class PluginInformation
	{
		// サーバはウィンドウごとに異なる
		//public static IPluginServer Server { get; set; }
		public static List<IPluginClient> Instances { get; private set; }

		static PluginInformation()
		{
			Instances = new List<IPluginClient>();
		}

		public static RegistryKey OpenRegistryKey(bool writable)
		{
			return OpenRegistryKey(typeof(PluginInformation), writable);
		}

		public static RegistryKey OpenRegistryKey(Type t, bool writable)
		{
			string ns = t.Namespace.Replace('.', '\\');
			string key = String.Format(@"Software\Quizo\QTTabBar\Plugins\Settings\{0}", ns);
			if (writable)
			{
				return Registry.CurrentUser.CreateSubKey(key);
			}
			else
			{
				return Registry.CurrentUser.OpenSubKey(key);
			}
		}
	}

	public class PluginClient : IPluginClient
	{
		protected IPluginServer m_server = null;
		protected IShellBrowser m_browser = null;

		public virtual bool HasOption
		{
			get
			{
				return false;
			}
		}

		public void Open(IPluginServer pluginServer, IShellBrowser shellBrowser)
		{
			m_server = pluginServer;
			m_browser = shellBrowser;

			OnOpen();
		}

		public virtual void Close(EndCode endCode)
		{
		}

		public virtual bool QueryShortcutKeys(out string[] actions)
		{
			actions = new string[] { };
			return false;
		}

		public virtual void OnOption()
		{
		}

		public virtual void OnShortcutKeyPressed(int index)
		{
		}

		public virtual void OnMenuItemClick(MenuType menuType, string menuText, ITab tab)
		{
		}

		protected virtual void OnOpen()
		{
		}
	}

	public class BarButton : PluginClient, IBarButton
	{
		public virtual bool ShowTextLabel
		{
			get
			{
				return false;
			}
		}

		public virtual string Text
		{
			get
			{
				return String.Empty;
			}
		}

		public virtual void InitializeItem()
		{
			// ボタンバーにこのボタンが追加されるたびに呼ばれます。
		}

		public virtual Image GetImage(bool fLarge)
		{
			return null;
		}

		public virtual void OnButtonClick()
		{
		}

	}

	public class BarDropButton : BarButton, IBarDropButton
	{
		public virtual bool IsSplitButton
		{
			get
			{
				return false;
			}
		}

		public virtual void OnDropDownItemClick(ToolStripItem item, MouseButtons mouseButton)
		{
		}

		public virtual void OnDropDownOpening(ToolStripDropDownMenu menu)
		{
		}
	}

	//public class BarCustomItem : BarButton, IBarCustomItem
	//{
	//    public ToolStripItem CreateItem(bool fLarge, QTPlugin.DisplayStyle displayStyle)
	//    {
	//        return null;
	//    }
	//}


}
